package com.asiainfo.complier.ui;

import com.asiainfo.complier.codemanger.CodeManager;
import com.asiainfo.complier.editor.CoderEditor;
import com.asiainfo.complier.editor.LineEditor;
import com.asiainfo.complier.editor.WordHighter;
import com.asiainfo.complier.helper.StringHelper;
import com.asiainfo.complier.helper.UIHelper;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.BadLocationException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class FindAndReplaceDlg extends JDialog {

    /**
     * FindAndReplaceDlg
     */
    private static final long serialVersionUID = 1410139313865830004L;
    private CodeManager manager;
    private JTextArea textArea;

    public FindAndReplaceDlg(JFrame parent, CodeManager manager) {
        super(parent);
        this.manager = manager;
        setTitle(UIHelper.getResource("lan_find_place"));
        initUI();
        CoderEditor editor = manager.getActiveCoderEditor();
        final LineEditor editor2 = editor.getActiveEditor();
        editor2.addCaretListener(new CaretListener() {

            public void caretUpdate(CaretEvent e) {
                if (objHiObject != null) {
                    editor2.getHighlighter().removeHighlight(objHiObject);
                    objHiObject = null;
                }
            }
        });

    }

    public boolean findNext() {
        return find(true);

    }

    private Object objHiObject;

    private boolean find(boolean forward) {
        CoderEditor editor = manager.getActiveCoderEditor();
        LineEditor editor2 = editor.getActiveEditor();
        int pos = editor2.getCaretPosition();
        String allTxt = editor2.getText();
        String findText = textArea.getText();

        if (forward) {
            int index = allTxt.indexOf(findText, pos + 1);

            if (index != -1) {
                editor2.setSelectionStart(index);
                editor2.setSelectionEnd(index + findText.length());
                editor2.moveCaretPosition(index);
                try {
                    if (objHiObject != null) {
                        editor2.getHighlighter().removeHighlight(objHiObject);
                        objHiObject = null;
                    }
                    objHiObject = editor2.getHighlighter()
                            .addHighlight(index, index + findText.length(),
                                    new WordHighter(editor2));
                } catch (BadLocationException e) {

                    e.printStackTrace();
                }
                return true;
            }
            return false;
        } else {
            int index = allTxt.lastIndexOf(findText, pos - 1);

            if (index != -1) {

                editor2.setSelectionStart(index);
                editor2.setSelectionEnd(index + findText.length());
                editor2.moveCaretPosition(index);

                try {
                    if (objHiObject != null) {
                        editor2.getHighlighter().removeHighlight(objHiObject);
                        objHiObject = null;
                    }

                    objHiObject = editor2.getHighlighter()
                            .addHighlight(index, index + findText.length(),
                                    new WordHighter(editor2));
                } catch (BadLocationException e) {

                    e.printStackTrace();
                }
                return true;
            }
            return false;
        }

    }

    public boolean findPrev() {
        return find(false);
    }

    private int getFindCounts() {
        CoderEditor editor = manager.getActiveCoderEditor();
        LineEditor editor2 = editor.getActiveEditor();
        int pos = 0;
        int counts = 0;
        String allTxt = editor2.getText();
        String findText = textArea.getText();
        if (StringHelper.isNullOrEmpty(findText))
            return 0;

        while (true) {
            int index = allTxt.indexOf(findText, pos);
            if (index != -1) {
                pos = index + findText.length();
                counts++;
            } else {
                break;
            }
        }
        return counts;
    }

    private void init() {
        CoderEditor editor = manager.getActiveCoderEditor();
        String txt = editor.getActiveEditor().getSelectedText();
        textArea.setText(txt);
        textArea.selectAll();
    }

    public void doModal() {

        this.setSize(460, 210);
        setResizable(false);
        UIHelper.centerWindow(this);
        this.setVisible(true);
        this.setModal(true);

    }

    private void initUI() {
        JPanel centeJPanel = new JPanel();
        JPanel rightJPanel = new JPanel();
        centeJPanel.setPreferredSize(new Dimension(276, -1));
        rightJPanel.setPreferredSize(new Dimension(120, -1));
        JLabel empyJLabel = new JLabel();
        empyJLabel.setPreferredSize(new Dimension(120, 12));
        JButton btlast = new JButton(UIHelper.getResource("lan_bt_up"));
        btlast.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent paramActionEvent) {
                if (StringHelper.isNullOrEmpty(textArea.getText())) {
                    JOptionPane.showMessageDialog(FindAndReplaceDlg.this,
                    		UIHelper.getResource("lan_txt_seelct"));
                    return;
                }
                if (findNext())
                    dispose();
                else
                    JOptionPane.showMessageDialog(FindAndReplaceDlg.this,
                            "can't find");
            }
        });
        JButton btPrev = new JButton(UIHelper.getResource("lan_bt_down"));
        btPrev.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent paramActionEvent) {

                if (StringHelper.isNullOrEmpty(textArea.getText())) {
                    JOptionPane.showMessageDialog(FindAndReplaceDlg.this,
                    		UIHelper.getResource("lan_txt_seelct"));
                    return;
                }
                if (findPrev())
                    dispose();
                else
                    JOptionPane.showMessageDialog(FindAndReplaceDlg.this,
                            "can't find");
            }
        });
        JButton btCount = new JButton(UIHelper.getResource("lan_all_count"));
        btCount.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent paramActionEvent) {
                int counts = getFindCounts();
                JOptionPane.showMessageDialog(FindAndReplaceDlg.this, counts
                        + " words  find  ");
            }
        });
        JButton btCose = new JButton(UIHelper.getResource("lan_all_exit"));

        btCose.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent paramActionEvent) {
                setVisible(false);
            }
        });

        rightJPanel.add(empyJLabel);
        rightJPanel.add(btPrev);
        rightJPanel.add(btlast);
        rightJPanel.add(btCount);
        rightJPanel.add(btCose);
        JScrollPane findScrollPane = new JScrollPane();

        textArea = new JTextArea();
        findScrollPane.getViewport().add(textArea);

        centeJPanel.setLayout(new BorderLayout());
        centeJPanel.setBorder(new EmptyBorder(0, 10, 0, 0));
        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 2));
        JCheckBox allWord = new JCheckBox(UIHelper.getResource("lan_all_word"));
        JCheckBox allWordCase = new JCheckBox(UIHelper.getResource("lan_all_word_case"));
        bottomPanel.add(allWord);
        bottomPanel.add(allWordCase);
        rightJPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

        JPanel titleJPanel = new JPanel();
        titleJPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 2));
        titleJPanel.add(new JLabel(UIHelper.getResource("lan_find_place")));

        centeJPanel.add(bottomPanel, BorderLayout.SOUTH);
        centeJPanel.add(findScrollPane, BorderLayout.CENTER);
        centeJPanel.add(titleJPanel, BorderLayout.NORTH);
        this.setLayout(new BorderLayout());

        this.getContentPane().add(centeJPanel, BorderLayout.CENTER);
        this.getContentPane().add(rightJPanel, BorderLayout.EAST);
        init();
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        this.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent paramWindowEvent) {
                setModal(false);
                setVisible(false);
            }

        });

    }

}
